package com.cap.bts.framework.auth.interceptor;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.cap.bts.commonfunc.common.util.UserUtil;
import com.cap.bts.framework.usermgnt.domain.User;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 初始化请求信息
 *
 *
 */
public class AccessInfoHandlerInterceptor extends HandlerInterceptorAdapter {

    private Logger logger = LoggerFactory.getLogger(AccessInfoHandlerInterceptor.class);

    private static final JSONObject JSONMAPPER = new JSONObject();

	public static String getBodyString(BufferedReader br) {
		String inputLine;
		StringBuilder str = new StringBuilder();
		try {
			while ((inputLine = br.readLine()) != null) {
				str.append(inputLine);
			}
			br.close();
		} catch (IOException e) {
		}
		return str.toString();
	}
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        long beginTime = System.nanoTime();//1、开始时间
        
        AccessLog accessLog = new AccessLog();

        accessLog.setStartTime(beginTime);
        accessLog.setRequestMethod(request.getMethod());
        accessLog.setParamsJson(JSONMAPPER.toJSONString(request.getParameterMap()));
        accessLog.setRequestUrl(request.getServletPath());
        accessLog.setHost(getIpAddr(request));
        accessLog.setReferer(request.getHeader("referer"));

        accessLog.setBody(IOUtils.toString(request.getInputStream(), "utf-8"));
        
        User user = UserUtil.getCurrentUser();
        
        if(user != null){
        	accessLog.setCurrentUserId(user.getId() + "");
        	accessLog.setCurrentUserName(user.getName());
        	accessLog.setCurrentDealerId(user.getDealerId() + "");
        }
        
        AccessInfoContext.setRequestLog(accessLog);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest req, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AccessLog accessLog = AccessInfoContext.getRequestLog();
        
        if(accessLog != null){
        	
        	accessLog.getConsumeTime();//3、消耗的时间
        	
        	AccessInfoContext.remove();
        	if(req.getRequestURI().endsWith(".js") || req.getRequestURI().endsWith(".css")
        			|| req.getRequestURI().endsWith(".jpg") || req.getRequestURI().endsWith(".gif")
        			|| req.getRequestURI().endsWith(".mp3") || req.getRequestURI().endsWith(".woff2")
        			|| req.getRequestURI().endsWith(".bmp") || req.getRequestURI().endsWith(".htm")
        			){
        		
        	}else{
        		logger.info("\n{}", accessLog.toString());
        	}
        }


    }



    /**
     *
     * @param request
     * @return
     */
    private static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }



}
